#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "jpeglib.h"

void compress_scanline(unsigned char *in, unsigned char *out, int np)
{
	int i, j;
	int r, g, b;
	unsigned char *ip, *op;

	ip = in;
	op = out;
	for (i = 0; i < np; i += 4) {
		r = g = b = 0;
		for (j = 0; j < 4; j++) {
			r += *ip++;
			g += *ip++;
			b += *ip++;
		}
		r = r / 4;
		g = g / 4;
		b = b / 4;
		for (j = 0; j < 4; j++) {
			*op++ = r;
			*op++ = g;
			*op++ = b;
		}
	}
//	fprintf(stderr, "compress: %d bytes, i:%d\n", (int)(op-out), i);
}

		
void frame_lowres(char *filespec1)
{
	struct jpeg_decompress_struct cinfo1;
	struct jpeg_compress_struct cinfo2;
	struct jpeg_error_mgr jerr1, jerr2;
	char ppmheader[256];
	int row_stride, row;
	char *filespec2;
	JSAMPARRAY buffer;
	JSAMPROW row_pointer[1];
	FILE *file1, *file2;

	filespec2 = "temp.jpg";

	file1 = fopen(filespec1, "rb");
	file2 = fopen(filespec2, "wb"); 
	if (!file1 || !file2) {
		fprintf(stderr, "error opening files\n");
		return;

	}

	cinfo1.err = jpeg_std_error(&jerr1);
	jpeg_create_decompress(&cinfo1);

	jpeg_stdio_src(&cinfo1, file1);

	jpeg_read_header(&cinfo1, TRUE);

	(void) jpeg_start_decompress(&cinfo1);

	if (cinfo1.output_components != 3) {
		fprintf(stderr, "Not an RGB image\n");
		return;
	}

	if (cinfo1.output_components != 3) {
		fprintf(stderr, "Requires RGB image\n");
		return;
	}
	if (cinfo1.output_width % 4) {
		fprintf(stderr, "Width must be multiple of 4\n");
		return;
	}

	cinfo2.err = jpeg_std_error(&jerr2);
	jpeg_create_compress(&cinfo2);

	jpeg_stdio_dest(&cinfo2, file2);

	cinfo2.image_width = cinfo1.image_width;      /* image width and height, in pixels */
	cinfo2.image_height = cinfo1.image_height;
	cinfo2.input_components = 3;           /* # of color components per pixel */
	cinfo2.in_color_space = JCS_RGB;       /* colorspace of input image */

	jpeg_set_defaults(&cinfo2);

	jpeg_set_quality(&cinfo2, 10, TRUE /* limit to baseline-JPEG values */);

	cinfo2.optimize_coding = TRUE;

	jpeg_start_compress(&cinfo2, TRUE);

	row_stride = cinfo1.output_width * cinfo1.output_components;
//	fprintf(stderr, "output_width:%d output_components:%d\n", cinfo1.output_width, cinfo1.output_components);
	buffer = (*cinfo1.mem->alloc_sarray)
		((j_common_ptr) &cinfo1, JPOOL_IMAGE, row_stride, 1);
	row_pointer[0] = malloc(row_stride);
	for (row = 0; cinfo1.output_scanline < cinfo1.output_height; row++) {
		(void) jpeg_read_scanlines(&cinfo1, buffer, 1);
		if ((row % 4) == 0)
			compress_scanline(buffer[0], row_pointer[0], cinfo1.output_width);
		(void) jpeg_write_scanlines(&cinfo2, row_pointer, 1);

	}
	(void) jpeg_finish_decompress(&cinfo1);
	jpeg_destroy_decompress(&cinfo1);

	jpeg_finish_compress(&cinfo2);

	fclose(file1);
	fclose(file2);

	unlink(filespec1);
	rename(filespec2, filespec1);
}
